package com.wangwenjun.concurrency.chapter14.copyonwritearraylist;

import org.junit.Test;

import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;

public class TestCopyOnWriteArrayList {

    /**
     * CopyOnWriteArrayList是ArrayList的线程安全版本
     * 它是线程安全的
     * @throws InterruptedException
     */
    @Test
    public void test01() throws InterruptedException {
        CountDownLatch cdl = new CountDownLatch(3);
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList();


        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 100000; i++) {
                list.add(i + "");
            }
            cdl.countDown();
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 100000; i++) {
                list.add(i + "");
            }
            cdl.countDown();
        });

        Thread t3 = new Thread(() -> {
            for (int i = 0; i < 100000; i++) {
                list.add(i + "");
            }
            cdl.countDown();
        });


        t1.start();
        t2.start();
        t3.start();

        cdl.await();

        System.out.println(list.size());
    }

    @Test
    public void test02(){
        Student s1 = new Student();
        Student s2 = new Student();
        CopyOnWriteArrayList<Student> list = new CopyOnWriteArrayList();
        list.add(s1);
        list.add(s2);
        System.out.println(s1 == list.get(0));
    }


    private class Student{

    }
}
